package cat.controller;

import cat.entity.Article;
import cat.entity.Comment;
import cat.entity.User;
import cat.service.ArticleService;
import cat.service.CommentService;
import cat.service.UserService;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class AdminController {
    @Resource  //用这个注解,声明要依赖于业务层的组件
    private UserService userService;
    @Resource
    private ArticleService articleService;
    @Resource
    private CommentService commentService;

    @RequestMapping("/loginVerify")
    public String login(HttpServletRequest request, Model model)
    {
        String username=request.getParameter("username");
        String passwrod=request.getParameter("password");
        String rememberme=request.getParameter("rememberme");

        User user= userService.getUserByNameOrEmail(username);

        if(user==null) {
            request.setAttribute("msg", "用户名错误");
            return "/login";
        }
        else if(!user.getUserPass().equals(passwrod)) {
            request.setAttribute("msg", "密码错误");
            return "/login";
        }
        else {
            //登录成功,把用户信息放到session 合局域中,方便以后使用
            request.getSession().setAttribute("session_user", user);

            //添加cookie 相关的信息 ....
            //更新用户的最后登录时间
            //更新用户的最后登录ip
								/*
								user.setUserLastLoginTime(new Date());
								user.setUserLastLoginIp(request.getRemoteAddr());
								userService.updateUser(user); */
        }

        List<Article> articleList = articleService.listRecentArticle(5);
        model.addAttribute("articleList",articleList);

        //首页要显示最新的5条评论信息列表
        List<Comment> commentList = commentService.listRecentComment(5);
        model.addAttribute("commentList",commentList);



        return "/index";
    }

    @RequestMapping("/delete/{commentId}")
    public String delete(@PathVariable Integer commentId,Model model){
        commentService.deleteComment(commentId);
        List<Article> articleList = articleService.listRecentArticle(5);
        model.addAttribute("articleList",articleList);

        //首页要显示最新的5条评论信息列表
        List<Comment> commentList = commentService.listRecentComment(5);
        model.addAttribute("commentList",commentList);
        return "/index";
    }

}
